package com.ruicar.afs.cloud.gateway.filter;

import com.ruicar.afs.cloud.common.core.holder.TransRequestContextHolder;
import com.ruicar.afs.cloud.common.core.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.HandlerFilterFunction;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class RequestFilterHandler implements HandlerFilterFunction {
	/**
	 * Apply this filter to the given handler function. The given
	 * {@linkplain HandlerFunction handler function} represents the next entity in the chain,
	 * and can be {@linkplain HandlerFunction#handle(ServerRequest) invoked} in order to
	 * proceed to this entity, or not invoked to block the chain.
	 *
	 * @param request the request
	 * @param next    the next handler or filter function in the chain
	 * @return the filtered response
	 */
	@Override
	public Mono filter(ServerRequest request, HandlerFunction next) {
		try {
			TransRequestContextHolder.bindSysClientInfo(RequestUtil.getClientInfo(request.headers().asHttpHeaders().toSingleValueMap()));
			return  next.handle(request);
		}finally {
			TransRequestContextHolder.clear();
		}
	}
}
